const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken, encryptPhone, decryptPhone, getNextId, logUserOperation } = require('../untils/untils');

router.get('/', authenticateToken, async (req, res) => {
    try {
        // 翻译关联员工
        const { username, emp_id } = req.query;
        let sql = `SELECT user.*,role.role_name,role.role_id FROM user JOIN user_role ON user.username = user_role.username JOIN role ON user_role.role_id = role.role_id WHERE 1 = 1`;
        if (username) {
            sql += ` AND user.username LIKE '%${username}%'`;
        }
        if (emp_id) {
            sql += ` AND user.emp_id = '${emp_id}'`;
        }
        let [result] = await db.execute(sql);

        const [emp_info] = await db.execute(`SELECT * FROM employee`);
        result.forEach(item => {
            item.emp_name = emp_info.find(emp => emp.emp_id === item.emp_id)?.emp_name || item.emp_id;
        });

        await logUserOperation(req, '查询', '获取用户列表', '获取用户列表成功', '成功');
        res.json({
            success: true,
            message: '获取用户列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取用户列表失败:', error);
        await logUserOperation(req, '查询', '获取用户列表', '获取用户列表失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取用户列表失败',
            error: error.message
        });
    }
});

// 添加用户
// { "username": "user", "role_id": "ROLE00001", "emp_id": "MG00001", "password": "abcd1234", "is_active": "是" }
router.put('/add', authenticateToken, async (req, res) => {
    try {
        const { username, emp_id, role_id, password, is_active } = req.body;


        let sql = `INSERT INTO user (username, emp_id, password, is_active) VALUES (?, ?, ?, ?)`;
        let params = [username, emp_id, password, is_active];
        const [result] = await db.execute(sql, params);

        // 添加用户角色关联
        let sql_role = `INSERT INTO user_role (username, role_id) VALUES (?, ?)`;
        let params_role = [username, role_id];
        const [result_role] = await db.execute(sql_role, params_role);

        await logUserOperation(req, '添加', '添加用户', '添加用户成功', '成功');
        res.json({
            success: true,
            message: '添加用户成功',
            data: result
        });
    } catch (error) {
        console.error('添加用户失败:', error);
        await logUserOperation(req, '添加', '添加用户', '添加用户失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '添加用户失败',
            error: error.message
        });
    }
});

// {"username":"hzp","role_id":"ROLE00002","emp_id":"MG00002","password":"a123456","is_active":"是"}
router.post('/update', authenticateToken, async (req, res) => {
    try {
        const { username, role_id, emp_id, password, is_active } = req.body;
        let sql = `UPDATE user SET emp_id = ?, password = ?, is_active = ? WHERE username = ?`;
        let params = [emp_id, password, is_active, username];
        const [result] = await db.execute(sql, params);


        // 修改用户角色关联
        let sql_role = `UPDATE user_role SET role_id = ? WHERE username = ?`;
        let params_role = [role_id, username];
        const [result_role] = await db.execute(sql_role, params_role);

        await logUserOperation(req, '更新', '更新用户', '更新用户成功', '成功');
        res.json({
            success: true,
            message: '修改用户成功',
            data: result
        });
    } catch (error) {
        await logUserOperation(req, '更新', '更新用户', '更新用户失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '修改用户失败',
            error: error.message
        });
    }
});

router.delete('/delete', authenticateToken, async (req, res) => {
    try {
        const { username } = req.query;


        let sql = `DELETE FROM user WHERE username = ?`;
        let params = [username];
        const [result] = await db.execute(sql, params);

        // 删除用户角色关联
        let sql_role = `DELETE FROM user_role WHERE username = ?`;
        let params_role = [username];
        const [result_role] = await db.execute(sql_role, params_role);



        await logUserOperation(req, '删除', '删除用户', '删除用户成功', '成功');
        res.json({
            success: true,
            message: '删除用户成功',
            data: result
        });
    } catch (error) {
        console.error('删除用户失败:', error);
        await logUserOperation(req, '删除', '删除用户', '删除用户失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '删除用户失败',
            error: error.message
        });
    }
});

// 获取角色列表
router.get('/role', authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT role_id as 'key', role_name as 'name' FROM role`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取角色列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取角色列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取角色列表失败',
            error: error.message
        });
    }
});

// 获取员工列表
router.get('/employee', authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT emp_id as 'key', emp_name as 'name' FROM employee`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取员工列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取员工列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取员工列表失败',
            error: error.message
        });
    }
});

// 获取查询项关联员工
router.get('/emp', authenticateToken, async (req, res) => {
    try {
        const [result] = await db.execute(`SELECT DISTINCT employee.emp_id, employee.emp_name FROM employee JOIN user ON employee.emp_id = user.emp_id`);
        res.json({
            success: true,
            data: result
        });
    } catch (error) {
        console.error('获取查询项关联员工失败:', error);
        res.status(500).json({
            success: false,
            message: '获取查询项关联员工失败',
            error: error.message
        });
    }
});


// 校验用户名是否唯一 不包含当前用户
router.get('/check_username', authenticateToken, async (req, res) => {
    try {
        const { username, isAdd } = req.query;
        if (isAdd == 'false') {
            res.json({
                success: true,
                message: '用户名可用'
            });
            return
        }
        const [result] = await db.execute(`SELECT * FROM user WHERE username = ?`, [username]);
        if (result.length > 0) {
            res.json({
                success: false,
                message: '用户名已存在'
            });
        } else {
            res.json({
                success: true,
                message: '用户名可用'
            });
        }
    } catch (error) {
        console.error('校验用户名是否存在失败:', error);
        res.status(500).json({
            success: false,
            message: '校验用户名是否存在失败',
            error: error.message
        });
    }
});


module.exports = router;